//
//  UIView+Helper.m
//  HeylinkPro
//
//  Created by 胡韩国 on 2023/3/3.
//  Copyright © 2023 鼎合丰. All rights reserved.
//

#import "UIView+Helper.h"
#import "HeaderConfig.h"
#import <objc/runtime.h>
#import "UIColor+hexString.h"

static const int UIViewTapActionKey;

@interface UIViewHelper :NSObject

@property (nonatomic, copy) void(^block)(id target);

- (void)tapAction:(UITapGestureRecognizer *)tap;

@end

@implementation UIViewHelper

- (void)tapAction:(UITapGestureRecognizer *)tap{
    if(self.block){
        self.block(tap.view);
    }
}

@end

@implementation UIView (Helper)

- (void)addActionWithBlock:(void(^)(UIView *target))block{
    UIViewHelper *helper = [UIViewHelper new];
    helper.block = block;
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:helper action:@selector(tapAction:)];
    [self addGestureRecognizer:tap];
    objc_setAssociatedObject(self, &UIViewTapActionKey, helper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIImage*)setBackColorImage:(NSArray * __nullable)colorArray rect:(CGRect)rect{
    
    if(!colorArray)colorArray = @[(id)HEXColor(@"12E6F5").CGColor,(id)[HEXColor(@"0885FF") CGColor]];
    UIImage *bgImage;
    
    
    
    CGSize size = CGSizeMake(rect.size.width == 0 ? 44:rect.size.width, rect.size.height==0?100:rect.size.height);
    UIGraphicsBeginImageContextWithOptions(size, YES, 1.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
    gradientLayer.frame = rect;
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 0);
    gradientLayer.locations = @[@(0.2),@(1.0)];//渐变点
    [gradientLayer setColors:colorArray];
    [gradientLayer renderInContext:context];
    bgImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return bgImage;
}

@end
